package com.github.zhp.web.infrastructure;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.EncodeException;
import io.vertx.core.json.JsonObject;
import io.vertx.core.spi.json.JsonCodec;

public class GsonCodec implements JsonCodec {
    private final Gson gson;
    private final Gson prettyGson;

    public GsonCodec() {
        gson = new GsonBuilder().create();
        prettyGson = new GsonBuilder().setPrettyPrinting().create();
    }

    @Override
    public <T> T fromString(String json, Class<T> clazz) throws DecodeException {
        return gson.fromJson(json, clazz);
    }

    @Override
    @SuppressWarnings(value = {"unchecked"})
    public <T> T fromBuffer(Buffer json, Class<T> clazz) throws DecodeException {
        String jsonStr = json.toString();
        if (clazz.equals(Object.class)) {
            return (T) gson.fromJson(jsonStr, JsonObject.class);
        }
        return gson.fromJson(jsonStr, clazz);
    }

    @Override
    public <T> T fromValue(Object json, Class<T> toValueType) {
        String jsonStr = gson.toJson(json);
        return gson.fromJson(jsonStr, toValueType);
    }

    @Override
    public String toString(Object object, boolean pretty) throws EncodeException {
        if (pretty) {
            return prettyGson.toJson(object);
        }
        return gson.toJson(object);
    }

    @Override
    public Buffer toBuffer(Object object, boolean pretty) throws EncodeException {
        String jsonStr;
        if (pretty) {
            jsonStr = prettyGson.toJson(object);
        } else {
            jsonStr = gson.toJson(object);
        }
        return Buffer.buffer(jsonStr);
    }
}
